<template>
  <div class="container mx-auto p-6">
    <h1 class="text-2xl font-bold mb-6">修改房源信息</h1>

    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="120px"
      class="max-w-3xl"
      @submit.prevent="submitForm"
    >
      <!-- 基础信息 -->
      <el-form-item label="房源标题" prop="title">
        <el-input v-model="form.title" placeholder="请输入房源标题" />
      </el-form-item>

      <el-form-item label="所在城市" prop="city">
        <el-select v-model="form.city" placeholder="请选择城市" class="w-full">
          <el-option
            v-for="city in cities"
            :key="city.value"
            :label="city.label"
            :value="city.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="详细地址" prop="address">
        <el-input v-model="form.address" placeholder="请输入详细地址" />
      </el-form-item>

      <el-form-item label="详细描述" prop="content">
        <el-input
          v-model="form.content"
          type="textarea"
          :rows="4"
          placeholder="请输入房源详细描述"
          maxlength="500"
          show-word-limit
        />
      </el-form-item>

      <!-- 租赁信息 -->
      <div class="grid grid-cols-2 gap-4">
        <el-form-item label="租赁类型" prop="rentType">
          <el-radio-group v-model="form.rentType">
            <el-radio label="whole">整租</el-radio>
            <el-radio label="share">合租</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="月租金" prop="monthRent">
          <el-input-number
            v-model="form.monthRent"
            :min="500"
            :max="20000"
            controls-position="right"
            class="w-full"
          />
        </el-form-item>
      </div>

      <!-- 房屋特征 -->
      <div class="grid grid-cols-2 gap-4">
        <el-form-item label="建筑面积" prop="area">
          <el-input-number
            v-model="form.area"
            :min="10"
            :max="500"
            controls-position="right"
            class="w-full"
          >
            <template #append>m²</template>
          </el-input-number>
        </el-form-item>
        <el-form-item label="朝向" prop="direction">
          <el-select
            v-model="form.direction"
            placeholder="请选择朝向"
            class="w-full"
          >
            <el-option
              v-for="item in directions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="房屋户型">
          <div class="flex gap-2">
            <el-form-item prop="bedroom" class="m-0">
              <el-input-number
                v-model="form.bedroom"
                :min="0"
                controls-position="right"
                placeholder="室"
              />
            </el-form-item>
            <el-form-item prop="livingRoom" class="m-0">
              <el-input-number
                v-model="form.livingRoom"
                :min="0"
                controls-position="right"
                placeholder="厅"
              />
            </el-form-item>
            <el-form-item prop="kitchen" class="m-0">
              <el-input-number
                v-model="form.kitchen"
                :min="0"
                controls-position="right"
                placeholder="厨"
              />
            </el-form-item>
            <el-form-item prop="toilet" class="m-0">
              <el-input-number
                v-model="form.toilet"
                :min="0"
                controls-position="right"
                placeholder="卫"
              />
            </el-form-item>
          </div>
        </el-form-item>
      </div>

      <!-- 楼层信息 -->
      <div class="grid grid-cols-2 gap-4">
        <el-form-item label="当前楼层" prop="floor">
          <el-input-number
            v-model="form.floor"
            :min="1"
            controls-position="right"
            class="w-full"
          />
        </el-form-item>

        <el-form-item label="总楼层" prop="maxFloor">
          <el-input-number
            v-model="form.maxFloor"
            :min="1"
            controls-position="right"
            class="w-full"
          />
        </el-form-item>
      </div>

      <div class="grid grid-cols-2 gap-4">
        <el-form-item label="建成年份" prop="completionYear">
          <el-input-number
            v-model="form.completionYear"
            :min="1900"
            :max="new Date().getFullYear()"
            :precision="0"
            controls-position="right"
            class="w-full"
            placeholder="请输入建成年份"
          />
        </el-form-item>
        <el-form-item label="房产证号" prop="certificate">
          <el-input
            v-model="form.certificate"
            placeholder="请输入房产证编号"
            maxlength="20"
          />
        </el-form-item>
      </div>

      <!-- 设施信息 -->
      <div class="grid grid-cols-2 gap-4">
        <el-form-item label="空调">
          <el-switch
            v-model="form.conditioner"
            active-text="有"
            inactive-text="无"
          />
        </el-form-item>

        <el-form-item label="电梯">
          <el-switch
            v-model="form.elevator"
            active-text="有"
            inactive-text="无"
          />
        </el-form-item>
      </div>

      <!-- 位置信息 -->
      <div class="grid grid-cols-2 gap-4">
        <el-form-item label="经度" prop="longitude">
          <el-input-number
            v-model="form.longitude"
            :precision="6"
            :step="0.000001"
            controls-position="right"
            class="w-full"
          />
        </el-form-item>

        <el-form-item label="纬度" prop="latitude">
          <el-input-number
            v-model="form.latitude"
            :precision="6"
            :step="0.000001"
            controls-position="right"
            class="w-full"
          />
        </el-form-item>
      </div>
      <div class="grid grid-cols-2 gap-4">
        <el-form-item label="联系人姓名" prop="contactName">
          <el-input v-model="form.contactName" placeholder="请输入联系人姓名" />
        </el-form-item>
        <el-form-item label="联系电话" prop="contactPhone">
          <el-input
            v-model="form.contactPhone"
            placeholder="请输入联系电话"
            maxlength="11"
          />
        </el-form-item>
      </div>

      <!-- 图片上传 -->
      <el-form-item label="房源图片" prop="images">
        <el-upload
          v-model:file-list="mergedImages"
          action="#"
          list-type="picture-card"
          :auto-upload="false"
          :on-change="handleUpload"
          :on-remove="handleRemove"
          multiple
          accept="image/*"
        >
          <el-icon><Plus /></el-icon>
          <template #file="{ file }">
            <div
              class="relative w-full h-full bg-gray-100 rounded-lg overflow-hidden"
            >
              <img
                :src="getImageUrl(file)"
                class="absolute inset-0 w-full h-full object-cover"
              />
              <span class="el-upload-list__item-actions absolute top-0 right-0">
                <el-icon
                  class="!text-red-500 hover:!text-red-700"
                  @click="handleRemove(file)"
                >
                  <Close />
                </el-icon>
              </span>
            </div>
          </template>
        </el-upload>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          size="large"
          native-type="submit"
          :loading="submitting"
        >
          保存修改
        </el-button>
        <el-button @click="goBack">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import { Plus, Close } from "@element-plus/icons-vue";
import api from "@/api";
import { useUserStore } from "@/stores/user";

const route = useRoute();
const router = useRouter();
const userStore = useUserStore();
const houseId = route.params.id;

// 数据状态
const form = reactive({
  title: "",
  city: "",
  address: "",
  rentType: "",
  monthRent: 0,
  area: 0,
  bedroom: 0,
  livingRoom: 0,
  kitchen: 0,
  toilet: 0,
  floor: 0,
  maxFloor: 0,
  conditioner: false,
  elevator: false,
  direction: "",
  contactName: "",
  contactPhone: "",
  content: "",
  completionYear: 0,
  certificate: "",
  longitude: 0,
  latitude: 0,
});
const existingImages = ref([]);
const newImages = ref([]);
const submitting = ref(false);
const mergedImages = ref([]);

const cities = [
  { label: "北京市", value: "北京" },
  { label: "上海市", value: "上海" },
  { label: "广州市", value: "广州" },
  { label: "深圳市", value: "深圳" },
];
const directions = [
  { label: "东", value: "东" },
  { label: "南", value: "南" },
  { label: "西", value: "西" },
  { label: "北", value: "北" },
  { label: "东南", value: "东南" },
  { label: "东北", value: "东北" },
  { label: "西南", value: "西南" },
  { label: "西北", value: "西北" },
];
const rules = {
  title: [
    { required: true, message: "请输入房源标题", trigger: "blur" },
    { min: 5, max: 50, message: "长度在5到50个字符", trigger: "blur" },
  ],
  city: { required: true, message: "请选择所在城市", trigger: "change" },
  address: { required: true, message: "请输入详细地址", trigger: "blur" },
  monthRent: { required: true, message: "请输入月租金", trigger: "blur" },
  area: { required: true, message: "请输入建筑面积", trigger: "blur" },
  floor: { required: true, message: "请输入当前楼层", trigger: "blur" },
  maxFloor: { required: true, message: "请输入总楼层数", trigger: "blur" },
  longitude: [
    { required: true, message: "请输入经度", trigger: "blur" },
    {
      validator: (_, v) => v >= -180 && v <= 180,
      message: "经度范围：-180 ~ 180",
      trigger: "blur",
    },
  ],
  latitude: [
    { required: true, message: "请输入纬度", trigger: "blur" },
    {
      validator: (_, v) => v >= -90 && v <= 90,
      message: "纬度范围：-90 ~ 90",
      trigger: "blur",
    },
  ],
  direction: { required: true, message: "请选择房屋朝向", trigger: "change" },
  contactName: [
    { required: true, message: "请输入联系人姓名", trigger: "blur" },
    { min: 2, max: 10, message: "姓名长度2-10个字符", trigger: "blur" },
  ],
  contactPhone: [
    { required: true, message: "请输入联系电话", trigger: "blur" },
    {
      pattern: /^(?:(?:\+|00)86)?1[3-9]\d{9}$/,
      message: "请输入有效的手机号码",
      trigger: "blur",
    },
  ],
  content: [
    { required: true, message: "请输入房源描述", trigger: "blur" },
    { min: 20, max: 500, message: "描述需20-500个字符", trigger: "blur" },
  ],
  completionYear: [
    { required: true, message: "请输入建成年份", trigger: "blur" },
    {
      validator: (_, v) => v >= 1900 && v <= new Date().getFullYear(),
      message: `年份范围：1900-${new Date().getFullYear()}`,
      trigger: "blur",
    },
  ],
};

// 加载房源数据
const loadData = async () => {
  try {
    const res = await api.house.getHouses({ id: houseId });
    if (res.data.data?.length === 0) {
      ElMessage.error("房源不存在");
      return router.push("/houses");
    }

    const data = res.data.data[0];

    form.status = data.status;

    // 填充表单数据
    Object.keys(form).forEach((key) => {
      if (data[key] !== undefined) {
        if (key === "conditioner" || key === "elevator") {
          form[key] = data[key] === 1;
        } else {
          form[key] = data[key];
        }
      }
    });

    // 处理图片
    existingImages.value = data.houseImageList.map((url) =>
      url.startsWith("http") ? url : `http://localhost:8080${url}`
    );

    // 合并现有图片到 mergedImages
    existingImages.value.forEach((url) => {
      mergedImages.value.push({
        uid: url,
        name: url.split("/").pop(),
        status: "done",
        url: url,
      });
    });
    console.log("源数据", data, mergedImages.value);
  } catch (error) {
    ElMessage.error("数据加载失败");
  }
};

// 获取图片URL
const getImageUrl = (file) => {
  // 优先显示本地预览
  if (file.raw) return URL.createObjectURL(file.raw);
  return file.url || "";
};

// 图片处理
const handleUpload = (file) => {
  mergedImages.value.push({
    ...file,
    uid: URL.createObjectURL(file.raw), // 生成唯一标识
    raw: file.raw, // 保留原始文件对象
    url: URL.createObjectURL(file.raw),
  });
};

// 修改图片删除处理逻辑
const handleRemove = (file) => {
  mergedImages.value = mergedImages.value.filter((f) => f.uid !== file.uid);
};

// UpdateHouse.vue 的 submitForm 方法
const submitForm = async () => {
  const formData = new FormData();

  // 1. 构造房屋数据（布尔转数字）
  const houseData = {
    ...form,
    conditioner: form.conditioner ? 1 : 0,
    elevator: form.elevator ? 1 : 0,
    status: form.status === -3 ? -2 : form.status,
  };

  // 2. 将 JSON 包装为 Blob 并设置类型
  const houseBlob = new Blob([JSON.stringify(houseData)], {
    type: "application/json", // 关键：强制指定类型
  });
  formData.append("house", houseBlob, "house.json"); // 第三个参数确保类型识别

  // 3. 处理图片
  const existingUrls = mergedImages.value
    .filter((img) => !img.raw)
    .map((img) => img.url);
  const newFiles = mergedImages.value
    .filter((img) => img.raw)
    .map((img) => img.raw);

  newFiles.forEach((file) => formData.append("images", file));
  formData.append("existingImages", JSON.stringify(existingUrls));

  if (form.status === -3) {
    api.house.updateStatus(houseId, -2);
  }

  // 4. 发送请求
  await api.house.updateHouse(houseId, formData);
  ElMessage.success(
    form.status === -3 ? "修改成功，已重新提交审核" : "修改成功"
  );
  router.push("/houselist");
};

// 返回上一页
const goBack = () => {
  router.go(-1);
};

// 初始化加载
onMounted(loadData);
</script>

<style scoped>
.container {
  background-color: #f8fafc;
  min-height: 100vh;
}
.el-form-item__label {
  @apply font-semibold text-gray-700;
}
.el-upload--picture-card,
.el-upload-list--picture-card .el-upload-list__item {
  width: 160px; /* 固定宽度 */
  height: 160px; /* 固定高度 */
  margin-right: 8px;
  margin-bottom: 8px;
  display: inline-flex;
  justify-content: center;
  align-items: center;
  border-radius: 8px;
  overflow: hidden;
  position: relative;
}

.el-upload-list__item-thumbnail {
  width: 100%;
  height: 100%;
  object-fit: cover; /* 使图片覆盖整个容器 */
}

.el-upload-list__item-actions {
  display: flex;
  justify-content: center;
  align-items: center;
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5); /* 半透明背景 */
  color: white;
  opacity: 0;
  transition: opacity 0.3s ease-in-out;
}

.el-upload-list__item:hover .el-upload-list__item-actions {
  opacity: 1;
}

.el-icon.Close {
  cursor: pointer;
  font-size: 24px;
  padding: 4px;
}

.el-upload--picture-card::before {
  content: "";
  display: block;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.1); /* 浅色背景 */
  z-index: 1;
}

.el-upload--picture-card i {
  font-size: 24px;
  color: #8c939d;
  line-height: 160px;
  z-index: 2;
}

.el-upload--picture-card:hover i {
  color: #409eff;
}

/* 确保图片容器内的图片正确显示 */
.el-upload-list__item img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

/* 按钮组定位 */
.el-form-item:last-child {
  @apply mt-8 pt-6 border-t border-gray-200; /* 底部操作区 */
}
</style>
